package com.wyj.utils

import android.net.Uri

/**
 * Created by Administrator on 2018/2/2.
 */

class URLUtils private constructor(internal var uri: Uri) {

    val host: String?
        get() = uri.host


    fun addTimeStamp(): URLUtils {
        return appendParams(TIME_STAMP, System.currentTimeMillis().toString() + "")
    }

    fun getParams(key: String): String? {
        return uri.getQueryParameter(key)
    }

    fun appendParams(key: String, value: String?): URLUtils {
        val str = getParams(key)
        uri = if (isNullOrEmpty(str)) {
            val builder = uri.buildUpon()
            builder.appendQueryParameter(key, value ?: "")
            builder.build()
        } else {
            Uri.parse(uri.toString().replace("\\b$key=[^&]*\\b".toRegex(), "$key=$value"))
        }
        return this
    }

    fun updateParams(key: String, value: String): URLUtils {
        return appendParams(key, value)
    }

    fun build(): String {
        return uri.toString()
    }

    companion object {
        private const val TIME_STAMP = "timeStamp"

        @JvmStatic
        fun with(url: String): URLUtils {
            return URLUtils(Uri.parse(url))
        }

        @JvmStatic
        fun isUrl(url: String?): Boolean {
            return url?.toLowerCase()?.startsWith("http") == true
        }
    }
}
